package com.ship.dispatch.controller.sys;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.FileUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.fob.SpFobTemplate;
import com.ship.dispatch.bean.fob.SpFobTemplateFlie;
import com.ship.dispatch.bean.sys.SysConstant;
import com.ship.dispatch.bo.fileTemplate.SpFobTemplateBO;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.vo.dto.FormTemplate;
import com.ship.dispatch.model.dto.fileTemplate.SpFobFileTemplateDto;
import com.ship.dispatch.model.dto.fileTemplate.SpFobTemplateDto;
import com.ship.dispatch.model.dto.fileTemplate.SpFobTemplateUpdateDto;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.SpFobTemplateFlieServer;
import com.ship.dispatch.service.fob.SpFobLabelItemService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import com.ship.dispatch.service.sys.SysConstantService;
import com.ship.dispatch.vo.fileTemplate.NodeVO;
import com.ship.dispatch.vo.fileTemplate.SpFobLabelItemVO;
import com.ship.dispatch.vo.fileTemplate.SpFobTemplateListVO;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ServerWebExchange;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/fileTemplate/")
@Api(value = "sysFileTemplate", tags = "邮件、文件模板前端控制器")
public class SysFileTemplateController {
    @Autowired
    private TaskService taskService;
    @Autowired
    private SpFobTemplateService fobTemplateService;
    @Autowired
    private SpFobTemplateFlieServer spFobTemplateFlieServer;
    @Autowired
    private SpFobLabelItemService labelItemService;
    @Autowired
    private SysConstantService constantService;
    @Autowired
    private ExportService exportService;
    @Value("${file_server.host}")
    private String fileServerHost;
    @Autowired
    private RemoteFileService remoteFileService;

    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    /**
     * 获取邮件模板应用节点
     *
     * @return
     */
    @GetMapping("getFormTemplates")
    public JsonResult getFormTemplates() {
        //List<NodeVO> nodeVOS = new ArrayList<>();
        List<NodeVO> nodeVOS = taskService.getAllTasks();
        /*List<FormTemplate> formTemplates = taskService.getFormTemplates();
        if(null != formTemplates && formTemplates.size()>0){
            formTemplates.stream().forEach(f->{
                NodeVO nodeVO = new NodeVO();
                BeanUtils.copyProperties(f,nodeVO);
                nodeVO.setTemplateUsage(f.getName());
                if(null == nodeVOS){
                    nodeVOS.add(nodeVO);
                }else{
                    if(nodeVOS.stream().filter(n->n.getName().equals(f.getName())).count()==0){
                        nodeVOS.add(nodeVO);
                    }
                }
            });
        }*/
        return JsonResult.success(nodeVOS);
    }

    /**
     * 获取邮件模板流程节点
     *
     * @return
     */
    @GetMapping(value = {"/getTemplatesFlowNodes/{name}", "/getTemplatesFlowNodes"})
    public JsonResult getTemplatesFlowNodes(@PathVariable(value = "name", required = false) String name) {
        List<NodeVO> nodeVOS = new ArrayList<>();
        List<String> flowIds = new LinkedList<>();
        List<SysConstant> constants = constantService.list(new LambdaQueryWrapper<SysConstant>()
                .eq(SysConstant::getType,"船运执行流程")
        );
        if(StringUtils.isNotBlank(name)){
            List<FormTemplate> formTemplates = taskService.getFormTemplates();
            if(null != formTemplates && formTemplates.size()>0){
                formTemplates.stream().filter(f->f.getName().equals(name)).forEach(f->{
                    String flowId = f.getId().split("-")[0];
                    flowIds.add(flowId);
                });
            }
        }
        if(null != constants && constants.size()>0){
            List<NodeVO> finalNodeVOS = nodeVOS;
            constants.stream().forEach(c->{
                NodeVO nodeVO = new NodeVO();
                if("1".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB001");
                }else if("2".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB002");
                }else if("3".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB003");
                }else if("4".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB004");
                }else if("5".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB005");
                }else if("6".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB006");
                }else if("7".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB007");
                }else if("8".equals(c.getConstValue().toString())){
                    nodeVO.setId("FOB008");
                }
                nodeVO.setName(c.getConstLabel());
                finalNodeVOS.add(nodeVO);
            });
            if(flowIds.size()>0){
                nodeVOS = finalNodeVOS.stream().filter(n->flowIds.contains(n.getId())).collect(Collectors.toList());
            }else{
                nodeVOS = finalNodeVOS;
            }
        }

        return JsonResult.success(nodeVOS);
    }

    /**
     * 新增文件模板
     *
     * @return
     */
    @ApiOperation(value = "新增文件模板")
    @PostMapping("saveSpFobTemplate")
    @Log(title = "新增文件模板",businessType = BusinessType.INSERT)
    public JsonResult saveSpFobTemplate(@RequestBody SpFobTemplateBO fobTemplateBO) {
        List<NodeVO> formTemplates = taskService.getAllTasks();
        JsonResult result = fobTemplateService.saveSpFobTemplate2(fobTemplateBO,formTemplates);
        return result;
    }

    /**
     * 邮件模板列表 分页
     * @param pageDto
     * @return
     */
    @PostMapping("page")
    public JsonResult<Page<SpFobTemplateListVO>> page(@RequestBody SpFobTemplateDto pageDto){
        Page page = new Page();
        page.setCurrent(pageDto.getPageNum());
        page.setSize(pageDto.getPageSize());
        page.setSearchCount(true);
        return fobTemplateService.getPage(page, pageDto);
    }

    /**
     * 获取邮件模板应用节点
     *
     * @return
     */
    @GetMapping("getFobTemplateInfo/{id}")
    public JsonResult getFobTemplateInfo(@PathVariable("id") Long id) {
        SpFobTemplateListVO fobTemplateListVO = fobTemplateService.getFobTemplateInfo(id);
        return JsonResult.success(fobTemplateListVO);
    }

    /**
     * 删除邮件模板
     *
     * @return
     */
    @DeleteMapping("removeFobTemplateById/{id}")
    @Log(title = "删除邮件模板",businessType = BusinessType.DELETE)
    public JsonResult removeFobTemplateById(@PathVariable("id") Long id) {
        fobTemplateService.removeFobTemplateById(id);
        return JsonResult.success();
    }

    /**
     * 邮件模板状态变更(也是修改方法)
     * @param fobTemplateUpdateDto
     * @return
     */
    @PostMapping("updateFobTemplateStatus")
    @Log(title = "修改邮件模板",businessType = BusinessType.UPDATE)
    public JsonResult updateFobTemplateStatus(@RequestBody SpFobTemplateUpdateDto fobTemplateUpdateDto){
       // List<FormTemplate> formTemplates = taskService.getFormTemplates();
        List<NodeVO> nodeVOS = taskService.getAllTasks();
        SpFobTemplate fobTemplate = fobTemplateService.updateFobTemplateStatus2(fobTemplateUpdateDto,nodeVOS);
        return JsonResult.success(fobTemplate);
    }

    /**
     * 获取所有可用标签
     * @param name
     * @return
     */
    @GetMapping(value = {"/getSpFobLabelItems/{name}", "/getSpFobLabelItems"})
    public JsonResult getSpFobLabelItems(@PathVariable(value = "name", required = false) String name) {
        List<SpFobLabelItemVO> fobLabelItemVOS = labelItemService.getSpFobLabelItems(name);
        return JsonResult.success(fobLabelItemVOS);
    }

    /**
     * 文件模板上传
     */
    @ApiOperation(value = "文件模板上传")
    @PostMapping("/upload")
    @Log(title = "文件模板上传",businessType = BusinessType.IMPORT)
    public JsonResult<Map> getFileInfo( @RequestParam(value = "file") MultipartFile file) throws IOException {
        FileUtils.checkFileName(file);
        String name = file.getOriginalFilename();
        String url = upload(file);
        SpFobTemplateFlie spFobTemplateFlie =new SpFobTemplateFlie();

        spFobTemplateFlie.setUrl(url);
        spFobTemplateFlie.setFileName(name);
        spFobTemplateFlie.setCreateBy(SecurityUtils.getUsername());
        spFobTemplateFlie.setCreateDate(new Date());
        spFobTemplateFlieServer.save(spFobTemplateFlie);

//        SpFobTemplateFlie excelFileName = spFobTemplateFlieServer.upload(file);
        Map map = new HashMap(4);
        map.put("fileName",name);
        map.put("id",spFobTemplateFlie.getId());
        map.put("content",url);
        return JsonResult.success(map);
    }

    /**
     * 文件模板列表信息导出
     * @param pageDto
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "文件模板列表信息导出")
    @PostMapping("fileInfoExport")
    @Log(title = "文件模板列表信息导出",businessType = BusinessType.EXPORT)
    public JsonResult FileInfoExport(@RequestBody SpFobFileTemplateDto pageDto) throws IOException{
        Page page = new Page();
//        page.setCurrent(pageDto.getPageNum());
//        page.setSize(pageDto.getPageSize());
        page.setSearchCount(true);
        String uri = fobTemplateService.getExportInfo(pageDto);
        return JsonResult.success(uri);
    }

    /**
     * 文件模板分页查询
     * @param pageDto
     * @return
     */
    @ApiOperation(value = "文件模板分页查询")
    @PostMapping("FilePage")
    public JsonResult<Page<SpFobTemplateListVO>> FilePage(@RequestBody SpFobFileTemplateDto pageDto){
        Page page = new Page();
        page.setCurrent(pageDto.getPageNum());
        page.setSize(pageDto.getPageSize());
        page.setSearchCount(true);
        return fobTemplateService.getFilePage(page, pageDto);
    }

    /**
     * 文件模板详细信息
     */
    @ApiOperation(value = "文件模板详细信息")
    @GetMapping("getFobFileTemplateInfo/{id}")
    public JsonResult getFobFileTemplateInfo(@PathVariable("id") Long id) {
        return fobTemplateService.getFobFlieTemplateInfo(id);
    }

    /**
     * 修改状态
     */
    @ApiOperation(value = "修改状态")
    @GetMapping("updateFobFlieTemplateStatus/{id}")
    @Log(title = "修改文件模板状态",businessType = BusinessType.UPDATE)
    public JsonResult updateFobFlieTemplateStatus(@PathVariable("id") Long id){
        return fobTemplateService.updateFobFlieTemplateStatus(id);
    }

    /**
     * 删除文件模板
     *
     * @return
     */
    @ApiOperation(value = "删除文件模板")
    @DeleteMapping("removeFobFlieTemplateById/{id}")
    @Log(title = "删除文件模板",businessType = BusinessType.DELETE)
    public JsonResult removeFobFlieTemplateById(@PathVariable("id") Long id) {
        fobTemplateService.removeFobTemplateById(id);
        spFobTemplateFlieServer.delByTemplateId(id);
        return JsonResult.success();
    }

    /**
     * 上传附件M
     * @return
     */
    public String upload(MultipartFile file){
        FileUtils.checkFileName(file);
        R<SysFile> result1 = remoteFileService.upload(file);
        if(result1.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String result = result1.getData().getHttpsUrl();;
        return result;
    }

}
